<template>
  <div id="login">
    <nav-vue title="登录" />
    <van-image
      width="80"
      height="80"
      round
      fit="cover"
      class="img"
      :src="require('../assets/images/timg.jpg')"
    />
    <!-- 登录表单 -->
    <van-form ref="formBox" @submit="onSubmit">
      <van-cell-group inset>
        <van-field
          v-model="username"
          name="phone"
          label="手机号"
          placeholder="请输入手机号"
          :rules="[{ required: true, message: '请填写手机号' },{ pattern: regPhone, message: '手机号格式不对哦~' },]"
        >
            <template #button>
                <van-button 
                    size="small"
                    :type="enable ? 'primary' : ''"
                    class="form-btn"
                    :disabled="!enable"
                    @click="sendOut"
                >{{ enable ? "发送验证码" : time }}</van-button>
            </template>
        </van-field>
        <van-field
          v-model="password"
          name="验证码"
          label="验证码"
          placeholder="请输入验证码"
          :rules="[{ required: true, message: '请填写验证码' },{ pattern: regPassword, message: '手机验证码格式不对哦~' },]"
        />
      </van-cell-group>
      <div style="margin: 20px 40px">
        <van-button round block type="primary" native-type="submit">
          立即登录/注册
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import NavVue from "@/components/Nav.vue";
import { reactive, toRefs, ref } from "vue";
import api from '../api/baseApi';
import { Toast } from "vant";
import { useStore } from 'vuex'
import { useRoute, useRouter } from 'vue-router'
export default {
  name: "LoginView",
  components: {
    NavVue,
  },
  setup() {
    const router = new useRouter(),
            store = new useStore(),
            route = new useRoute()
    const loginFrom = reactive({
      username: "",
      password: "",
      enable: true,
      time: "60s",
    });
    let formBox = ref(null);
    const onSubmit = async() => {
      const { code, token } = await api.login(loginFrom.username, loginFrom.password)
      if (+code !== 0) {
        Toast("小主，很遗憾，当前登录失败了~");
        formBox.value.resetValidation();
        loginFrom.code = "";
        return;
      }
      // 存储token信息
      localStorage.setItem("token", token);
      store.commit("changeIsLogin", true);
      store.dispatch("changeInfoAsync");
      store.commit("changeStoreList", null);
      Toast("小主真棒，当前登录成功喽~");
      // 页面跳转
      // 直接跳转到 首页 不友好，在收藏时，登录完成后应跳转到对应的文章详情处
      // router.push('/home') 
      // 跳转到指定地址
      let from = route.query.from;
      // 这里replace之后，前一个还是详情页！！
      if (from) {
        // router.replace(`/${from}`);
        router.back()
        return;
      }
      router.replace(`/person`);
    };
    const sendOut = async() => {
        try{
            // 校验手机号格式
            await formBox.value.validate("phone");
            const { code } = await api.phoneCode(loginFrom.username)
            // console.log(data);
            if(+code !== 0){
                Toast("小主，当前网络繁忙，请稍后再试哦~");
                return;
            }
            // 开启倒计时
            loginFrom.enable = false
            loginFrom.time = `10s`
            let n = 10
            let timer = setInterval(() => {
                // 不断变化time值，倒计时结束改变enable状态
                n--
                if(n == 0){
                    clearInterval(timer)
                    loginFrom.enable = true
                    return
                }
                loginFrom.time = `${n}s`
            }, 1000)
        }catch(e){}
    }
    return {
      ...toRefs(loginFrom),
      onSubmit,
      sendOut,
      regPhone: /^1\d{10}$/,
      regPassword: /^\d{6}$/,
      formBox
    };
  },
};
</script>

<style lang="less" scoped>
#login{
    .van-cell{
        height: 70px;
    }
    .img{
        display: block;
        margin: 20px auto;
    }
    .form-btn {
        width: 78px;
  }
}
</style>
